﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Com.JunCaiSoft.AutoMapper;
using Com.JunCaiSoft.Common.AssistClass;
using Com.JunCaiSoft.Common.Controller;
using Com.JunCaiSoft.Common.Enums;
using Com.JunCaiSoft.Common.ExchangeData;
using Com.JunCaiSoft.Common.Model;
using Com.JunCaiSoft.Common.Struct;
using Com.JunCaiSoft.Permission.Entity;
using Com.JunCaiSoft.Permission.IDao;
using Com.JunCaiSoft.Permission.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Org.BouncyCastle.Math.EC.Rfc7748;

namespace Com.JunCaiSoft.API.Permission.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class UserController : BaseController<UserView,UserItem,User,Guid>
    {
        public UserController(IUserDao userdao) : base(userdao)
        {

        }
        /// <summary>
        /// 按用户ID批量删除
        /// </summary>
        /// <param name="Id">用户ID列表</param>
        /// <returns></returns>
        [HttpPatch]
        public virtual async Task<ActionResult> DeleteList(IEnumerable<Guid> Id)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();
                int result = DaoAsync.DeleteListAsync<User>(x => Id.Contains(x.Id)).Result;

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                await DaoAsync.dbContext.Database.CommitTransactionAsync();
            }
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> ListByPageAsync(int pageIndex, int pageSize,String keyword)
        {
            try
            {
                QueryData<UserItem> result = new QueryData<UserItem>();

                if(keyword != null && keyword != "")
                {
                    var tmp = await DaoAsync.ListByPageAsync(x => x.RealName.Contains(keyword) || x.UserName.Contains(keyword), x => x.CreateTime, pageIndex, pageSize, OrderbyType.desc);
                    result.totalCount = tmp.totalCount;
                    result.items = tmp.items.ToList().MapTo<List<User>, List<UserItem>>(tmp.items.ToList());
                }
                else
                {
                    var tmp = (await DaoAsync.ListByPageAsync(x => x.CreateTime, pageIndex, pageSize, OrderbyType.desc));
                    result.totalCount = tmp.totalCount;
                    result.items = tmp.items.ToList().MapTo<List<User>, List<UserItem>>(tmp.items.ToList());
                }
                
                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 获取权限树
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> GetAllAuthorizes()
        {
            return await Task.Run(() => Content(JsonConvert.SerializeObject(APIConfig.GetAuthorizes())));
        }
        [HttpPost]
        public override async Task<ActionResult> CreateAsync(UserView entity)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();

                var one = entity.MapTo<User>();

                one.Password = HashPassword.MD5Password(entity.Password);

                var result = await DaoAsync.InsertAsync(one);

                one.Positions = new List<Position> { 
                    new Position{ Name = entity.CurrentPlayRole.Name,RoleId = entity.CurrentPlayRole.Id,UserId = one.Id,CreateTime = DateTime.Now }
                };

                foreach (var item in one.Positions)
                {
                    await DaoAsync.InsertAsync<Position>(item);
                }
                
                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                await DaoAsync.dbContext.Database.RollbackTransactionAsync();
                throw e;
            }
            finally
            {
                await DaoAsync.dbContext.Database.CommitTransactionAsync();
            }
        }
        public override async Task<ActionResult> UpdateAsync(UpdateEntity<UserView> entityModel)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();

                var orginal = await DaoAsync.GetAsync(entityModel.Id);

                var one = entityModel.entity.MapTo<User>();

                one.Password = orginal.Password;

                var result = await DaoAsync.UpdateAsync(one,entityModel.Id);

                var positionList = await DaoAsync.ListAsync<Position>(x => x.UserId == one.Id , new OrderModelField[]{ });

                await DaoAsync.DeleteListAsync<Position>(x => positionList.Contains(x));

                one.Positions = new List<Position> {
                    new Position{ Name = entityModel.entity.CurrentPlayRole.Name,RoleId = entityModel.entity.CurrentPlayRole.Id,UserId = one.Id,CreateTime = DateTime.Now }
                };

                foreach (var item in one.Positions)
                {
                    await DaoAsync.InsertAsync<Position>(item);
                }

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                await DaoAsync.dbContext.Database.RollbackTransactionAsync();
                throw e;
            }
            finally
            {
                await DaoAsync.dbContext.Database.CommitTransactionAsync();
            }
        }
        [HttpGet]
        public override async Task<ActionResult> GetAsync(Guid Id)
        {
            try
            {
                var getOne = await DaoAsync.GetAsync(Id);

                if(getOne == null)
                {
                    throw new Exception("用户不存在！");
                }

                var one = getOne.MapTo<UserView>();

                getOne.Positions = await DaoAsync.ListAsync<Position>(x => x.UserId == one.Id, new OrderModelField[] { });

                if (getOne.Positions != null)
                {
                    var defaultPosition = getOne.Positions.FirstOrDefault();

                    if(defaultPosition != null)
                    {
                        defaultPosition.Role = await DaoAsync.GetAsync<Role>(x => x.Id == defaultPosition.RoleId);
                        one.CurrentPlayRole = defaultPosition != null ? defaultPosition.Role : new Role();
                    }
                    else
                    {
                        one.CurrentPlayRole = new Role();
                    }
                }
                else
                {
                    one.CurrentPlayRole = new Role();
                }
                return await Task.Run(() => Content(JsonConvert.SerializeObject(one)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
}
